﻿namespace AnyOffice.Components
{
    using log4net;
    using Microsoft.ApplicationBlocks.Data;
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web;

    public class SysLog
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ConfigManager));

        public static void Log(SqlConnection conn, int type, string remark)
        {
            string userId = string.Empty;
            if (HttpContext.Current.User.Identity.IsAuthenticated) userId = HttpContext.Current.User.Identity.Name;
            Log(conn, userId, type, remark);
        }

        public static void Log(SqlConnection conn, string userId, int type, string remark)
        {
            try
            {
                string str = "INSERT [dbo].[Sys_Log] ([UserId],[LogTime],[Ip],[Type],[Remark]) VALUES (@UserId, @LogTime, @Ip, @Type, @Remark)";
                SqlParameter[] parameterArray = new SqlParameter[5];
                parameterArray[0] = new SqlParameter("@UserId", SqlDbType.NVarChar, 20);
                if (userId == string.Empty)
                    parameterArray[0].Value = DBNull.Value;
                else
                    parameterArray[0].Value = userId;
                parameterArray[1] = new SqlParameter("@LogTime", SqlDbType.DateTime);
                parameterArray[1].Value = DateTime.Now;
                parameterArray[2] = new SqlParameter("@Ip", SqlDbType.NVarChar, 20);
                parameterArray[2].Value = HttpContext.Current.Request.UserHostAddress;
                parameterArray[3] = new SqlParameter("@Type", SqlDbType.Int);
                parameterArray[3].Value = type;
                parameterArray[4] = new SqlParameter("@Remark", SqlDbType.NText);
                parameterArray[4].Value = remark;
                SqlHelper.ExecuteNonQuery(conn, CommandType.Text, str, parameterArray);
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled) { log.Error("", exception); }
            }
        }

        public enum LogType
        {
            AdminResetPassword = 11,
            Attendance = 13,
            ChangePassword = 14,
            DeptAdd = 3,
            DeptDelete = 5,
            DeptEdit = 4,
            IpError = 9,
            LogDisabled = 0x10,
            Login = 1,
            LoginPasswordError = 2,
            Logoff = 15,
            SystemResCallBack = 12,
            UKeyError = 0x11,
            UserAdd = 6,
            UserDelete = 8,
            UserEdit = 7,
            UserIdError = 10
        }
    }
}

